package indzcraft.loader;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import fast.mvc.View;


public class IndzCraftLoader {
	
	HashMap<String,Integer> items = new HashMap<String,Integer>();
	HashMap<String,Item> itemData = new HashMap<String,Item>();
	BaseStats base = new BaseStats();
	RaceDB raceDB = new RaceDB();
	GemDB gemDB;
	EnchantDB enchantDB = new EnchantDB();
	SocketBonusDB socketbonusDB = new SocketBonusDB();
	ReforgeDB reforgeDB = new ReforgeDB();
	ItemSetDB itemSetDB = new ItemSetDB();
	GearBuffDB gearBuffDB = new GearBuffDB();
	GlyphDB glyphDB = new GlyphDB();
	
	Equipment equipment = new Equipment();
	
	Database db;
	
	private String wowheadPrefix = "mop";
	
	public void load2(String playername,String server,String region,boolean _new) throws JSONException{
		
		base = new BaseStats();
		equipment = new Equipment();
		
		String json = loadURL(region,server,playername);
		System.out.println(json);
		JSONObject js = null;
		File dbDir = new File("./db/");
		if(!dbDir.exists())
			dbDir.mkdir();
		File file = new File("./db/" + region.toLowerCase() + "-" + server.toLowerCase()+"-"+playername.toLowerCase()+".character");
		try {
			js = new JSONObject(json);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		try {
			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
			out.write(json);
			out.flush();
			out.close();
			//System.out.println("flush out");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		//System.out.println(js.toString(1));
		JSONObject items = (JSONObject) js.get("items");
		for ( Iterator<?> i = items.keys(); i.hasNext(); )
		{
			String s = (String) i.next();
			Object item = items.get(s);
			if(item instanceof Integer){
				//System.out.println(s + ": (int) " + item.toString());
			}
			else {
				int id = ((JSONObject)item).getInt("id");
				this.items.put(s, id);
			}
		}
		for( String name: this.items.keySet() )
	    {
			int itemid = this.items.get(name);
			Item baseItem = getItemFromWOWHEAD(itemid);
			//System.out.println(name + ": "+ itemid);
			ItemEquipped item = new ItemEquipped();
			item.setItem(baseItem);
			
			// enchant etc.
			JSONObject iteme = new JSONObject();
			if(items.has(name))
				iteme = (JSONObject) items.get(name);
			
			JSONObject tooltip = null;
			Enchant e = null;
			if(iteme.has("tooltipParams")){
				tooltip = (JSONObject) iteme.get("tooltipParams");
			
				if(tooltip.has("enchant")){
					int enchantid = tooltip.getInt("enchant");
					e = enchantDB.getEnchant(enchantid);
					if(e != null){
						item.setEnchant(e);
					}
				} else {
					item.setEnchant(null);
				}
				if(tooltip.has("extraSocket") && tooltip.getBoolean("extraSocket")){
					int i = item.getItem().getNumSockets();
					item.getItem().gemSlot[i] = "PRISMATIC";
				}else{
					int i = item.getItem().getNumSockets();
					if(i < item.getItem().gemSlot.length){
						item.getItem().gemSlot[i] = "";
					}
				}
				if(tooltip.has("gem0")){
	    		   int gemid = tooltip.getInt("gem0");
	    		   Gem g = gemDB.getGem(gemid);
	    		   item.setGem(0, g);
				}else {
					item.setGem(0, null);
				}
				if(tooltip.has("gem1")){
	    		   int gemid = tooltip.getInt("gem1");
	    		   Gem g = gemDB.getGem(gemid);
	    		   item.setGem(1, g);
				}else {
					item.setGem(1, null);
				}
				if(tooltip.has("gem2")){
	    		   int gemid = tooltip.getInt("gem2");
	    		   Gem g = gemDB.getGem(gemid);
	    		   item.setGem(2, g);
				}else {
					item.setGem(2, null);
				}
				if(tooltip.has("reforge")){
					int reforgeid = tooltip.getInt("reforge");
					Reforge r = reforgeDB.getReforge(reforgeid);
					item.setReforge(r);
				} else {
					item.setReforge(new Reforge());
				}
			}
	       
			if(item.getItem().getDps() > 0){
				String type = item.getItem().getWeaponTypeName();
				String enchant = "";
				if(e != null){
					enchant = e.getName(); 
				}
				if(name.equals("mainHand")){ // mainHand
					base.setMH(new Weapon(item.getItem().getSpeed(),item.getItem().getDps(),type,enchant));
				}else if(name.equals("offHand")){ // offHand
					base.setOH(new Weapon(item.getItem().getSpeed(),item.getItem().getDps(),type,enchant));
				}
			}
			
			if(item.getItem().getGearBuff() != null)
				base.addGearBuff(item.getItem().getGearBuff());
			
			equipment.put(Slot.valueOf(name), item);
			this.db.put(item.getItem().getId(), baseItem);
	    }
		
		// Race
		base.setRace(raceDB.getRace(js.getInt("race")).getName());
		
		// Professions
		JSONObject profession = js.getJSONObject("professions");
		JSONArray professions = profession.getJSONArray("primary");
		for(int i = 0;i < professions.length(); i++)
		{
			JSONObject prof = (JSONObject) professions.get(i);
			System.out.println("prof: " + prof.getString("name"));
			base.addProfession(prof.getString("name"));
		}
		
		// talents
		JSONArray talents = (JSONArray) js.get("talents");
		//System.out.println(talents.length());
		for(int i = 0;i < talents.length(); i++)
		{
			JSONObject spec = (JSONObject) talents.get(i);
			//System.out.println(spec.toString(1));
			if((spec.has("selected") && spec.getBoolean("selected"))){
				if(spec.has("spec")){
					JSONObject spec2 = spec.getJSONObject("spec");
					this.base.setSpec(Spec.valueOf(spec2.getString("name")));
					this.base.setGlyphs(spec.getString("calcGlyph"));
				} else {
					this.base.setSpec(Spec.Combat);
				}
			}else{
				if(spec.has("spec")){
					JSONObject spec2 = spec.getJSONObject("spec");
					this.base.setOffSpec(Spec.valueOf(spec2.getString("name")));
					this.base.setOffGlyphs(spec.getString("calcGlyph"));
				} else {
					this.base.setOffSpec(Spec.Subtlety);
				}
			}
		}
		
		JSONObject stats = (JSONObject) js.get("stats");
		//System.out.println(stats.toString(1));
		
		base.incExp(stats.getInt("expertiseRating"));
		double agi = stats.getInt("agi")/1.05;
		if(this.base.getSpec() == Spec.Subtlety){
			agi = agi/1.3;
		}
		base.incAgi((int)Math.ceil(agi));
		//base.incAgi(stats.getInt("agi"));
		base.incStr(stats.getInt("str"));
		base.incCrit(stats.getInt("critRating"));
		base.incHaste(stats.getInt("hasteRating"));
		base.incHit(stats.getInt("hitRating"));
		base.incMastery(stats.getInt("masteryRating"));
		base.incAp(190); // FIXME: from where are the 190 the enchant??? or base 190ap????
		
		System.out.println(js.getString("name") + " - Level " + js.getInt("level"));
		System.out.println("str: " + base.getStr());
		System.out.println("agi: " + base.getAgi());
		System.out.println("ap: " + base.getAp());
		System.out.println("crit: " + base.getCrit());
		System.out.println("hit: " + base.getHit());
		System.out.println("exp: " + base.getExp());
		System.out.println("haste: " + base.getHaste());
		System.out.println("mastery: " + base.getMastery());
		
		for( String name: this.base.getSetItems().keySet() ) {
			System.out.println(name + ": " + this.base.getSetItems().get(name) + " piece/s");
	    }
		for( String name: this.base.getGearBuffs() ) {
			System.out.print(name + ", ");
	    }
		System.out.println();
	}
	
	public IndzCraftLoader() {
		base = new BaseStats();
		equipment = new Equipment();
		gemDB = new GemDB(this);
		populateGems();
 
		//http://#{prefix}.wowhead.com/items?filter=qu=4;minle=346;maxle=358;ub=4;cr=21;crs=1;crv=0
	}

	private String loadURL(String region, String server, String playername) {
		
		String url = "http://"+region+".battle.net/api/wow/character/"+server+"/"+playername+"?fields=items,talents,stats,professions";
		System.out.println("http://"+region+".battle.net/api/wow/character/"+server+"/"+playername+"?fields=items,talents,stats,professions");
		InputStream is = null;
		BufferedReader rd = null;
		try {
			is = new URL(url).openStream();
			rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			//System.out.println("no internet connection, try to read the file from hdd");
			View.addConsole("no internet connection, try to read the file from hdd");
			//e.printStackTrace();
			BufferedReader in;
			try {
				File file = new File("./db/" + region.toLowerCase() + "-" + server.toLowerCase()+"-"+playername.toLowerCase()+".character");
				in = new BufferedReader(new FileReader(file));
				String content = in.readLine();
				in.close();
				return content;
			} catch (IOException es) {
				//es.printStackTrace();
				System.out.println("no local profile found");
				View.addConsole("no local profile found");
			}
		}
		String cp = "";
		StringBuilder sb = new StringBuilder();
		try {
			while ((cp = rd.readLine()) != null) {
			      sb.append(cp);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	private String loadURL(String url) {
		InputStream is = null;
		BufferedReader rd = null;
		try {
			is = new URL(url).openStream();
			rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String cp = "";
		StringBuilder sb = new StringBuilder();
		try {
			while ((cp = rd.readLine()) != null) {
			      sb.append(cp);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	public static String getCharacterDataFromElement(Element e) {
		Node child = e.getFirstChild();
		if (child instanceof CharacterData) {
		   CharacterData cd = (CharacterData) child;
		   return cd.getData();
		}
		return "?";
	}
	
	public SocketBonus getSocketBonus(int item_id){
		SocketBonus sb = null;
		try {
			JSONObject data = getItemDataWowHead(item_id);
			//System.out.println(data.toString(1));
			if(data.has("socketbonus")){
				int socketbonusid = data.getInt("socketbonus");
				sb = socketbonusDB.getSocketBonus(socketbonusid);
			}
		}
		catch (Exception e) {
	        e.printStackTrace();
	    }
		return sb;
	}
	
	public JSONObject getItemDataWowHead(int item_id){
		
		JSONObject stats = null;
		String json = "";
		
		File file = new File("./wowhead/"+item_id+".xml");
		if(!file.exists()){
			json = loadURL("http://"+wowheadPrefix+".wowhead.com/item=" + item_id + "&xml");
		
			try {
				PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
				out.write(json);
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else{
			BufferedReader in;
			try {
				in = (new BufferedReader(new FileReader(file)));
				json = in.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//System.out.println(json);
		try {
	        DocumentBuilderFactory dbf =
	            DocumentBuilderFactory.newInstance();
	        DocumentBuilder db = dbf.newDocumentBuilder();
	        InputSource is = new InputSource();
	        is.setCharacterStream(new StringReader(json));

	        Document doc = db.parse(is);
	        NodeList nodes = doc.getElementsByTagName("jsonEquip");
	        NodeList nodes2 = doc.getElementsByTagName("json");
	        
	        NodeList nodes3 = doc.getElementsByTagName("name");
	        NodeList nodes4 = doc.getElementsByTagName("icon");
	        
	        NodeList nodes5 = doc.getElementsByTagName("htmlTooltip");
	        
	        NodeList nodes6 = doc.getElementsByTagName("quality");

	        Element element = (Element) nodes.item(0);
	        if(element != null){
		        stats = new JSONObject("{" + element.getTextContent()+ "}");
		        Element element2 = (Element) nodes2.item(0);
		        JSONObject stats2 = new JSONObject("{" + element2.getTextContent()+ "}");
		        stats.put("extra", stats2);
	           
		        Element element3 = (Element) nodes3.item(0);
		        String stats3 = element3.getTextContent();
		        stats.put("name", stats3);
		        
		        Element element4 = (Element) nodes4.item(0);
		        String stats4 = element4.getTextContent();
		        stats.put("icon", stats4);
		        
		        Element element5 = (Element) nodes5.item(0);
		        String stats5 = element5.getTextContent();
		        stats.put("tooltip", stats5);
		        
		        Element element6 = (Element) nodes6.item(0);
		        String stats6 = element6.getAttribute("id");
		        stats.put("quality", stats6);
	        }
	    }
	    catch (Exception e) {
	    	System.out.println(item_id);
	        e.printStackTrace();
	    }
	    return stats;
	}
	
	public JSONObject getGemDataWowHead(int item_id){
		
		JSONObject stats = null;
		String json = "";
		
		File file = new File("./gems/"+item_id+".xml");
		if(!file.exists()){
			json = loadURL("http://"+wowheadPrefix+".wowhead.com/item=" + item_id + "&xml");
		
			try {
				//System.out.println("Write to db: " + id);
				//File file = new File("./wowhead/"+item_id+".xml");
				PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
				out.write(json);
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else{
			BufferedReader in;
			try {
				in = (new BufferedReader(new FileReader(file)));
				json = in.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//System.out.println(json);
		try {
	        DocumentBuilderFactory dbf =
	            DocumentBuilderFactory.newInstance();
	        DocumentBuilder db = dbf.newDocumentBuilder();
	        InputSource is = new InputSource();
	        is.setCharacterStream(new StringReader(json));

	        Document doc = db.parse(is);
	        NodeList nodes = doc.getElementsByTagName("jsonEquip");
	        NodeList nodes2 = doc.getElementsByTagName("json");
	        
	        NodeList nodes3 = doc.getElementsByTagName("name");
	        NodeList nodes4 = doc.getElementsByTagName("icon");
	        
	        NodeList nodes6 = doc.getElementsByTagName("quality");

	        Element element = (Element) nodes.item(0);
	        if(element != null){
		        stats = new JSONObject("{" + element.getTextContent()+ "}");
		        Element element2 = (Element) nodes2.item(0);
		        JSONObject stats2 = new JSONObject("{" + element2.getTextContent()+ "}");
		        stats.put("extra", stats2);
	           
		        Element element3 = (Element) nodes3.item(0);
		        String stats3 = element3.getTextContent();
		        stats.put("name", stats3);
		        
		        Element element4 = (Element) nodes4.item(0);
		        String stats4 = element4.getTextContent();
		        stats.put("icon", stats4);
		        
		        Element element6 = (Element) nodes6.item(0);
		        String stats6 = element6.getAttribute("id");
		        stats.put("quality", stats6);
	        }
	    }
	    catch (Exception e) {
	    	System.out.println(item_id);
	    	System.out.println(json);
	        e.printStackTrace();
	    }
	    return stats;
	}
	
	public String getWoWHeadTooltip(int item_id){
//		BufferedReader in =(new BufferedReader(new FileReader(file)));
//		String s = in.readLine();
		
		String tooltip = "";
		String json = "";
		File file = new File("./wowhead/"+item_id+".xml");
		if(file.exists()){
			BufferedReader in;
			try {
				in = (new BufferedReader(new FileReader(file)));
				json = in.readLine();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else{
			json = loadURL("http://"+wowheadPrefix+".wowhead.com/item=" + item_id + "&xml");
			try {
				//System.out.println("Write to db: " + id);
				file = new File("./wowhead/"+item_id+".xml");
				PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
				out.write(json);
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		//System.out.println(json);
		try {
	        DocumentBuilderFactory dbf =
	            DocumentBuilderFactory.newInstance();
	        DocumentBuilder db = dbf.newDocumentBuilder();
	        InputSource is = new InputSource();
	        is.setCharacterStream(new StringReader(json));

	        Document doc = db.parse(is);
	        NodeList nodes = doc.getElementsByTagName("htmlTooltip");

	        Element element = (Element) nodes.item(0);
           
	        tooltip = element.getTextContent();
	    }
	    catch (Exception e) {
	        e.printStackTrace();
	    }
	    return tooltip;
	}
	
	public JSONObject getItemDataBattleNet(int item_id){
		
		JSONObject stats = null;
		
		String json = loadURL("http://eu.battle.net/api/wow/item/" + item_id);
		//System.out.println(json);
		try {
           stats = new JSONObject(json);
	    }
	    catch (Exception e) {
	        e.printStackTrace();
	    }
	    return stats;
	}
	
	public Item getItemFromWOWHEAD(int itemid){
		Item item = new Item();
		
		JSONObject data = getItemDataWowHead(itemid);
		JSONObject extra;
		try {
			extra = data.getJSONObject("extra");
			
			item.setName(data.getString("name"));
			item.setIcon(data.getString("icon"));
			item.setTooltip(data.getString("tooltip"));
			item.setQuality(data.getInt("quality"));
			if(data.has("str"))
				item.setStr(data.getInt("str"));
			if(data.has("agi"))
				item.setAgi(data.getInt("agi"));
			if(data.has("sta"))
				item.setSta(data.getInt("sta"));
			if(data.has("hitrtng"))
				item.setHit(data.getInt("hitrtng"));
			if(data.has("critstrkrtng"))
				item.setCrit(data.getInt("critstrkrtng"));
			if(data.has("hastertng"))
				item.setHaste(data.getInt("hastertng"));
			if(data.has("exprtng"))
				item.setExp(data.getInt("exprtng"));
			if(data.has("mastrtng"))
				item.setMastery(data.getInt("mastrtng"));
			
			if(extra.has("id"))
				item.setId(extra.getInt("id"));
			if(data.has("dps"))
				item.setDps(data.getDouble("dps"));
			if(data.has("mledmgmax"))
				item.setMaxDmg(data.getInt("mledmgmax"));
			if(data.has("mledmgmin"))
				item.setMinDmg(data.getInt("mledmgmin"));
			if(data.has("speed"))
				item.setSpeed(data.getDouble("speed"));
			if(extra.has("classs"))
				item.setItemClass(extra.getInt("classs"));
			if(extra.has("level"))
				item.setItemLevel(extra.getInt("level"));
			if(extra.has("subclass"))
				item.setItemSubClass(extra.getInt("subclass"));
			if(extra.has("slot")){
				//item.setInventoryType(extra.getInt("slot"));
				item.setInventorySlot(extra.getInt("slot"));
			}
			
			// socket colors and socketbonus
			if(data.has("nsockets"))
				item.setNumSockets(data.getInt("nsockets"));
			if(data.has("socket1"))
				item.gemSlot[0] = Gem.SocketColors[data.getInt("socket1")];
			if(data.has("socket2"))
				item.gemSlot[1] = Gem.SocketColors[data.getInt("socket2")];
			if(data.has("socket3"))
				item.gemSlot[2] = Gem.SocketColors[data.getInt("socket3")];
			if(data.has("socketbonus")){
				item.socketBonus = socketbonusDB.getSocketBonus(data.getInt("socketbonus"));
				if(item.socketBonus == null){
					System.out.println(data.getString("name") + " " + data.getInt("socketbonus"));
				}
			}
			if(data.has("reqskill"))
				item.setReqSkill(data.getInt("reqskill"));
			if(data.has("itemset"))
				item.setSet(itemSetDB.getItemSetByItemId(itemid));
			GearBuffDB.GearBuff gb = gearBuffDB.getGearBuff(itemid);
			if(gb != null){
				item.setGearBuff(gb.getName());
			}
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			return null;
		}
		
		return item;
	}
	
	public Gem getGemFromWOWHEAD(int id){
		Gem gem = new Gem();
		
		JSONObject data = getGemDataWowHead(id);
		JSONObject extra;
		try {
			extra = data.getJSONObject("extra");

			//System.out.println(data.toString(1));
			
			gem.setName(data.getString("name"));
			gem.setIcon(data.getString("icon"));
			gem.setQuality(data.getInt("quality"));
			if(data.has("str"))
				gem.setStr(data.getInt("str"));
			if(data.has("agi"))
				gem.setAgi(data.getInt("agi"));
			if(data.has("sta"))
				gem.setSta(data.getInt("sta"));
			if(data.has("hitrtng"))
				gem.setHit(data.getInt("hitrtng"));
			if(data.has("critstrkrtng"))
				gem.setCrit(data.getInt("critstrkrtng"));
			if(data.has("hastertng"))
				gem.setHaste(data.getInt("hastertng"));
			if(data.has("exprtng"))
				gem.setExp(data.getInt("exprtng"));
			if(data.has("mastrtng"))
				gem.setMastery(data.getInt("mastrtng"));
			
			if(extra.has("id"))
				gem.setId(extra.getInt("id"));
			if(extra.has("subclass"))
				gem.setType(extra.getInt("subclass"));
			if(data.has("reqskill")){
				gem.setReqSkill(data.getInt("reqskill"));
			}
			if(gearBuffDB.isCritMetaGem(id))
				gem.setGearBuff("metagem_critdmg");

		} catch (JSONException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			//e.printStackTrace();
			return null;
		}
		
		return gem;
	}
	
	public BaseStats getBase(){
		return base;
	}
	
	public HashMap<String, Integer> getItems(){
		return items;
	}

	public Equipment getEquipment() {
		return equipment;
	}
	
	public void setDatabase(Database db){
		this.db = db;
		
		
		/*populateItems("http://"+wowheadPrefix+".wowhead.com/items?filter=qu=4;minle=346;maxle=358;ub=4;cr=21;crs=1;crv=0");
		populateItems("http://"+wowheadPrefix+".wowhead.com/items?filter=qu=4;minle=359;maxle=371;ub=4;cr=21;crs=1;crv=0");
		populateItems("http://"+wowheadPrefix+".wowhead.com/items?filter=qu=4;minle=372;maxle=410;ub=4;cr=21;crs=1;crv=0");*/
		
		//populateItems("http://"+wowheadPrefix+".wowhead.com/items?filter=qu=3;minle=346;ub=4;cr=21;crs=1;crv=0");
		
		//populateItems("http://"+wowheadPrefix+".wowhead.com/items?filter=qu=4;minle=359;cr=13;crs=1;crv=0");
		
//		populateItems("http://"+wowheadPrefix+".wowhead.com/items?filter=qu=4;minle=372;maxle=500;ub=4;cr=21;crs=1;crv=0");
//		populateItems("http://"+wowheadPrefix+".wowhead.com/items?filter=qu=4;minle=501;maxle=600;ub=4;cr=21;crs=1;crv=0");
//		
//		populateItems("http://"+wowheadPrefix+".wowhead.com/items?filter=qu=3;minle=372;maxle=500;ub=4;cr=21;crs=1;crv=0");
//		populateItems("http://"+wowheadPrefix+".wowhead.com/items?filter=qu=3;minle=501;maxle=600;ub=4;cr=21;crs=1;crv=0");
		
		// trinkets mop
//		db.get(87057); // bottle of inifinite stars
//		db.get(86132);
//		db.get(86791);
//		db.get(87574);
//		db.get(81265);
//		db.get(81267);
//		db.get(75274);
//		db.get(87495);
//		
//		db.get(77534);
//		
//		db.get(77530); // eng trinket: Ghost Iron Dragonling
//		
//		db.get(73643); // gladi insigna
	}
	
	@SuppressWarnings("unused")
	private void populateItems(String url1){
		String url = loadURL(url1);
		Pattern pattern = Pattern.compile("\\_\\[(\\d*)\\]=\\{.*?\\}");
		Matcher matcher = pattern.matcher(url);
		while (matcher.find()) {
			String s = matcher.group(1);
			//System.out.println(s);
			int i = Integer.parseInt(s);
			db.get(i);
		}
	}
	
	@SuppressWarnings("unused")
	private void populateGems(){
		 String url = loadURL("http://"+wowheadPrefix+".wowhead.com/items=3?filter=qu=2:3;minle=86;maxle=90;eb=1");
		 //String url = loadURL("http://"+wowheadPrefix+".wowhead.com/items=3?filter=qu=3:4:5;minle=81;maxle=85;eb=1");
		 Pattern pattern = Pattern.compile("\\_\\[(\\d*)\\]=\\{.*?\\}");
		 //System.out.println(pattern.toString());
		 Matcher matcher = pattern.matcher(url);
		 while (matcher.find()) {
			 String s = matcher.group(1);
			 //System.out.println(s);
			 int i = Integer.parseInt(s);
			 gemDB.getGem(i);
		 }
		 
		 gemDB.getGem(89873); // legendary gem
	}
	
	public Database getDatabase(){
		return db;
	}

	public GemDB getGemDB() {
		return gemDB;
	}

	public EnchantDB getEnchantDB() {
		return enchantDB;
	}

	public ReforgeDB getReforgeDB() {
		return reforgeDB;
	}
	
	public GlyphDB getGlyphDB() {
		return glyphDB;
	}

	public RaceDB getRaceDB() {
		return raceDB;
	}

	public void save(Equipment equipment) {
		JSONObject js;
		long time = System.currentTimeMillis() / 1000;
		File file = new File("./db/" + time + ".character");
		js = new JSONObject(equipment.equipment);
		
		try {
			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
			out.write(js.toString());
			out.flush();
			out.close();
			System.out.println("flush out");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String[] getProfiles() {
		List<String> profiles = new ArrayList<String>();
		File file = new File("./db/");
		if(file.exists()){
			System.out.println("Path /db/ exists");
			File[] files = file.listFiles();
			for(int i = 0;i< files.length;i++){
				if(files[i].isFile()){
					profiles.add(files[i].getName());
				}
			}
		}
		return (String[])profiles.toArray(new String[profiles.size()]);
	}
}
